package metadata

import (
	"context"

	"github.com/go-kratos/kratos/v2/metadata"
)

func GetServerValue(ctx context.Context, key string) (string, bool) {
	if md, ok := metadata.FromServerContext(ctx); ok {
		v, ok := md[key]
		return v, ok
	}
	return "", false
}

func ServerValue(ctx context.Context, key string, def ...string) (re string) {
	if v, ok := GetServerValue(ctx, "x-md-local-"+key); ok {
		return v
	} else if v, ok = GetServerValue(ctx, "x-md-global-"+key); ok {
		return v
	} else if v, ok = GetServerValue(ctx, "x-md-"+key); ok {
		return v
	} else if len(def) > 0 {
		return def[0]
	}
	return ""
}

func ServerName(ctx context.Context) (re string) {
	if v, ok := GetServerValue(ctx, "x-md-service-name"); ok && v != "" {
		return v
	} else if v, ok = GetServerValue(ctx, "x-md-local-app-name"); ok {
		return v
	}
	return ""
}

func IsDeBugRequest(ctx context.Context) bool {
	return ServerValue(ctx, "debug") != ""
}
